package mware_lib.ns;

import java.io.IOException;
import java.util.HashMap;

import mware_lib.communication.*;

public class LocalNameServer implements Runnable {

	private Thread thread;
	private volatile boolean running;

	private int sPort;

	private HashMap<String, Data> remoteObjects;

	public LocalNameServer(int sPort) {
		this.sPort = sPort;
		this.running = true;
		remoteObjects = new HashMap<String, Data>();
	}

	public void run() {

		try {
			Server server = new Server(this.sPort);
			while (running) {
				// Wait for connection and then get ObjectStream
				server.accept();
				ObjectStream os = server.getObjectStream();
				Object o = os.receive();
				NSWorker worker = new NSWorker(remoteObjects, o, os);
				thread = new Thread(worker);
				thread.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void terminate() {
		this.running = false;
	}

}
